<!--
adsFileUpload页面没有修改弹窗,新增修改删除功能都需要联调
-->
<template>
  <div v-loading="loading" element-loading-text="加载中。。。">
    <el-card>
      <el-form ref='QueryForm' :model='QueryForm'  size='mini'  label-position="top">
        <el-row :gutter="10">
          <el-col  :lg="4" :md="6">
            <el-form-item label='机构编号'  prop='branchNum'>
            <el-select v-model="QueryForm.branchNum" filterable placeholder="请选择机构" >
              <el-option
              v-for="item in branchNum"
              :key="item.orgno"
              :label="item.orgno+'-'+item.cname"
              :value="item.orgno"
              :disabled="item.disabled">
              </el-option></el-select>
            </el-form-item>
          </el-col>
          <el-col  :lg="4" :md="6">
            <el-form-item label='广告编号'  prop='adNo'>
              <el-input v-model="QueryForm.adNo" placeholder="请输入广告编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col  :lg="2" :md="3" class="searchBtnMarginTop">
            <el-button type='primary' size='mini' icon='el-icon-search' @click="queryModel">查询</el-button>
          </el-col>
          <el-col  :lg="2" :md="3" class="searchBtnMarginTop">
            <el-button type='warning' size='mini' icon='el-icon-refresh'
            @click="resetForm('QueryForm')">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-row>
        <el-col :md="3" :lg="2">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="dialogOptions.isShow=true" v-if="btnPermission('Button_AD_Add')">新增</el-button>
        </el-col>
        <el-col :md="3" :lg="2">
          <el-button type="primary" size="mini" icon="el-icon-edit" :disabled="!(selection.length==1)" @click="checkPermission('1')"
            v-if="btnPermission('Button_AD_Edit')">修改</el-button>
        </el-col>
        <el-col :md="3" :lg="2">
          <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="!(selection.length==1)" @click="checkPermission()"
            v-if="btnPermission('Button_AD_Delete')">删除</el-button>
        </el-col>
      </el-row>
      <el-table ref="menuItemList" :data='menuItemList' header-row-class-name="tableHeaderClass" class="tableMarginTop"
        @selection-change="selectList" border>
        <el-table-column type="selection" width="40" fixed></el-table-column>
        <el-table-column prop='Brno' :formatter="dataFormat" label='机构编号' min-width='200px'></el-table-column>
        <el-table-column prop='AdNo' label='广告编号' min-width='110px'></el-table-column>
        <el-table-column prop='AdType' :formatter="dataFormat" label='广告类型' min-width='110px'></el-table-column>
        <el-table-column prop='AdName' label='广告名称' min-width='110px'></el-table-column>
        <el-table-column prop='AdContent' label='文件路径' min-width='200px'></el-table-column>
        <el-table-column prop='Remark' label='文件描述' min-width='200px'></el-table-column>
        <el-table-column prop='OperDate' label='上传时间' min-width='110px'></el-table-column>
        <el-table-column prop='OperUserID' label='上传用户' min-width='90px'></el-table-column>
        <el-table-column label="预览" align="center" fixed="right" width="80">
          <template slot-scope="scope">
            <el-button type="text" size="mini" v-if="scope.row.AdType != 'C'" @click="dialogDetail(scope, menuItemList)">预览</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column prop='DeviceType' label='是否启用' min-width='107px'></el-table-column>
               <el-table-column prop='DevAssortmentName' label='开始日期' min-width='107px'></el-table-column>
               <el-table-column prop='DevIp' label='结束日期' min-width='107px'></el-table-column>
               <el-table-column prop='DeviceRunState' label='开始时间' min-width='107px'></el-table-column>
               <el-table-column prop='DeviceRunState' label='结束时间' min-width='107px'></el-table-column> -->

      </el-table>
      <div class="box" style="text-align:right;margin-top:10px">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="currentPage" :page-sizes="[10, 20, 50,100]" :page-size="pageSize" layout="total, prev, pager, next, jumper"
          :total="tableTotal">
        </el-pagination>
      </div>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible" :lock-scroll=false @close="dialogDetailClose">
      <div v-loading="loadingImg" style="text-align:center;">
        <h4 v-if="loadingImgError">加载图片失败</h4>
        <img style="width:100%;min-height:340px;position:relative;" :src="dialogImageUrl" alt="" @load="loadingImg=false"
          @error="loadingImgFalse">
      </div>
    </el-dialog>
    <el-dialog :visible.sync="deleteCheckPopStatu" :lock-scroll=false>
      <div v-loading="loading">
        因为图片已发布且在播放时间内，所以下列图片不能被删除
        <el-table :data="deleteCheckData" style="width: 100%;" max-height="400">
          <el-table-column prop="adName" label="图片名称">
          </el-table-column>
          <el-table-column prop="fileDesc" label="图片描述">
          </el-table-column>
          <el-table-column prop="operUserId" label="上传用户">
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="deleteCheckPopStatu = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="deleteHandle">继续删除</el-button>
      </div>
    </el-dialog>
    <component :is='dialogList.addAdsFileUpload' :option='dialogOptions' @succ="queryModel"></component>
    <component :is='dialogList.editAdsFileUp' :option='dialogOptionsUpdate' :selected-item='selectedItem'
      :edit-check-data="editCheckData" @succ="queryModel"></component>
  </div>
</template>

<script>
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import addAdsFileUpload from "./dialog/addAdsFileUpload";
  import editAdsFileUp from "./dialog/updateAdsFile";
  //通讯相关
  import request from "@/common/utils/request";
  import toolBox from "@/common/utils/toolBox";
  import branchList from "@/message/shared/branch-list"; //机构号
  import adUploadTableIns from "@/message/resourceManage/advertising/ad-upload-table";
  import adUploadDeleteIns from "@/message/resourceManage/advertising/ad-upload-delete";
  import editShowIns from "@/message/resourceManage/advertising/ad-upload-editShow";
  import influencedIns from "@/message/resourceManage/advertising/ad-upload-editCheck";
  import delInfluencedIns from "@/message/resourceManage/advertising/ad-upload-deleteCheck";

  export default {
    data() {
      return {
        loading: false,
        loadingImg: false,
        loadingImgError: false,
        deleteCheckData: [],
        deleteCheckPopStatu: false,
        dialogVisible: false,
        dialogImageUrl: "",
        dialogList: {
          addAdsFileUpload,
          editAdsFileUp
        },
        dialogOptions: {
          isShow: false
        },
        dialogOptionsUpdate: {
          isShow: false,
          branchList: [],
        },
        // checkedUser: false,
        // isDisabledDel: false,
        selection: [],
        selectedItem: {},
          QueryForm: {
          //查询表单
          branchNum: "",
          adNo: ""
        },
        branchNum: [],
        brnoMap: {},
        adTypeMap: {"P":"图片","V":"视频","C":"文字"},
        permission: {},

        menuItemList: [],
        tableTotal: 0,
        currentPage: 1,
        pageSize: getGlobalParams.get("PageSize"),
        editCheckData: []
      };
    },
    created() {
      this.queryBranchNum();
      this.queryModel();
    },
    methods: {
      queryBranchNum() {
        let resBody = new branchList();
        resBody.data.orgno = this.$store.getters.BranchNum;
        request(resBody)
          .then(response => {
            if (response.APP_HEAD.ReturnCode === "000000") {
              this.branchNum = response.RspInfo.Result || []
              this.dialogOptionsUpdate.branchList = response.RspInfo.Result || [];
              this.permission = toolBox.objArray2Hash((response.RspInfo.Result || []), "orgno");
              this.brnoMap = response.RspInfo.orgMap || {};
            } else {
              this.$message({
                type: "warning",
                message: SYS_HEAD.ReturnMessage
              });
            }
          })
          .catch(error => {
            console.error("查询错误", error);
          });
      },
      dataFormat(row, column) {
        //枚举设备形式
        if (column.property == "Brno")
          return row[column.property] + "-" + this.brnoMap[row[column.property]];
        if (column.property == "AdType")
          return this.adTypeMap[row[column.property]];
      },
      loadingImgFalse() {
        this.loadingImg = false;
        this.loadingImgError = true;
      },
      //预览功能
      dialogDetail(scope) {
        this.loadingImgError = false;
        this.dialogVisible = true;
        this.loadingImg = true;
        //这里的地址在globalParams中配置  需要和后台的存放文件的配置统一
        //在这里只取图片下行地址中的ip地址
        var IpAddress =
          getGlobalParams.get("ADImgFileDownloadAddress");
        //在表格中返回的内容只有相对地址，所以需要使用ip地址拼接
        this.dialogImageUrl = IpAddress + scope.row.AdContent;
      },
      dialogDetailClose() {
        this.dialogImageUrl = "";
      },
      handleSizeChange() {
        this.selection = [];
        this.queryModel();
      },
      handleCurrentChange() {
        this.selection = [];
        this.queryModel();
      },
      resetForm() {
        this.$refs.QueryForm.resetFields();
      },
      selectList(selection) {
        this.selection = selection;
      },
      deleteHandle() {
        this.$confirm("您确定是否要删除选中项，删除后将不能恢复", "删除", {
            cancelButtonText: "取消",
            confirmButtonText: "确定",
            type: "warning"
          })
          .then(() => {
            this.deleteAd();
          })
          .catch(function () {
            return;
          });
      },
      async queryModel() {
        this.loading = true;
        let resBody = new adUploadTableIns();
        resBody.data.Brno = this.QueryForm.branchNum == "" ? this.$store.getters.BranchNum : this.QueryForm.branchNum;
        resBody.data.AdNo = this.QueryForm.adNo;
        resBody.data.QueryPageNo = this.currentPage;
        resBody.data.QueryRowNum = this.pageSize;
        let response = await request(resBody);
        this.loading = false;
        if (response.SYS_HEAD.ReturnCode == "000000") {
          var resultArr = response.RspInfo.resultSet;
          this.menuItemList = resultArr || [];
          this.tableTotal = response.RspInfo.total;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" +
              response.SYS_HEAD.ReturnCode +
              "，错误信息：" +
              response.SYS_HEAD.ReturnMessage
          });
        }
      },
      async deleteAd() {
        this.loading = true;
        let resBody = new adUploadDeleteIns();
        var tempArr = [];
        for (var k in this.selection) {
          tempArr.push(this.selection[k].AdNo);
        }
        resBody.data.adNo = tempArr.join(",");
        let response = await request(resBody);
        this.loading = false;
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.queryModel();
          this.deleteCheckPopStatu = false;
          if (response.RspInfo.resuleSet.alertMessage == "0") {
            this.$message({
              type: "success",
              message: "删除成功"
            });
          } else {
            this.$message({
              type: "error",
              message: "该广告文件使用期尚未过期，无法删除！"
            });
          }
        } else {
          this.$message({
            type: "error",
            message: "请求失败:" + response.SYS_HEAD.ReturnMessage
          });
        }
      },
      async editShowAd() {
        this.loading = true;
        let resBody = new editShowIns();
        var tempArr = [];
        resBody.data.adNo = this.selection[0].AdNo + "";
        let response = await request(resBody);
        this.loading = false;
        if (response.SYS_HEAD.ReturnCode == "000000") {
          var tempObj = response.RspInfo.resultSet[0];
          this.selectedItem = {
            adNo: this.selection[0].AdNo,
            adName: this.selection[0].AdName,
            endDate: tempObj.endDate,
            endTime: tempObj.endTime,
            startDate: tempObj.startDate,
            startTime: tempObj.startTime,
            isEnable: !Number(tempObj.isEnabled), //0为启用
            brno: tempObj.brno,
            remark: tempObj.remark,
            adContentre: tempObj.adContentre,
            adType: tempObj.adType
          };
          await this.influencedDev();
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" +
              response.SYS_HEAD.ReturnCode +
              "，错误信息：" +
              response.SYS_HEAD.ReturnMessage
          });
        }
      },
      checkPermission(val) {
        if (this.permission[this.selection.Brno]) {
          if (val) {
            this.editShowAd();
          } else {
            this.influencedDelDev();
          }
        } else {
          this.$message({
            type: "warning",
            message: "权限不足,无法修改！"
          });
        }
      },
      //查询被影响的机具的方法
      async influencedDelDev() {
        this.loading = true;
        let resBody = new delInfluencedIns();
        // console.log(this.selectedItem);
        var tempArr = [];
        for (var k in this.selection) {
          tempArr.push(this.selection[k].AdNo);
        }
        resBody.data.adNo = tempArr.join(",");

        let response = await request(resBody);
        this.loading = false;
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.deleteCheckData = response.RspInfo.resultSet;
          if (this.deleteCheckData.length == 0) {
            this.deleteHandle();
            return;
          }
          this.deleteCheckPopStatu = true;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" +
              response.SYS_HEAD.ReturnCode +
              "，错误信息：" +
              response.SYS_HEAD.ReturnMessage
          });
        }
      },
      async influencedDev() {
        this.loading = true;
        let resBody = new influencedIns();
        resBody.data.adNo = this.selection[0].AdNo + "";

        let response = await request(resBody);
        this.loading = false;
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.editCheckData = response.RspInfo.resultSet;
          // this.innerVisible=true;
          this.dialogOptionsUpdate.isShow = true;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" +
              response.SYS_HEAD.ReturnCode +
              "，错误信息：" +
              response.SYS_HEAD.ReturnMessage
          });
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  // .dialog-text {
  //   display: inline-block;
  //   width: 100%;
  //   text-align: center;
  //   color: red;
  //   font-size: 18px;
  // }
</style>
